import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '舒尔特方格训练',
      theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: true),
      home: const SchulteGridApp(),
    );
  }
}

class SchulteGridApp extends StatefulWidget {
  const SchulteGridApp({super.key});

  @override
  State<SchulteGridApp> createState() => _SchulteGridAppState();
}

class _SchulteGridAppState extends State<SchulteGridApp> {
  int selectedSize = 5;
  List<int> numbers = [];
  List<int> shuffledNumbers = [];
  int currentNumber = 1;
  bool isGameStarted = false;
  bool isGameCompleted = false;

  Timer? _timer;
  int _seconds = 0;

  // 最好成绩
  int? bestTime5x5;
  int? bestTime7x7;
  int? bestTime9x9;

  @override
  void initState() {
    super.initState();
    _loadBestTimes();
    _generateNumbers();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _loadBestTimes() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      bestTime5x5 = prefs.getInt('best_5x5');
      bestTime7x7 = prefs.getInt('best_7x7');
      bestTime9x9 = prefs.getInt('best_9x9');
    });
  }

  void _saveBestTime(int size, int time) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String key = 'best_${size}x$size';
    int? currentBest = prefs.getInt(key);

    if (currentBest == null || time < currentBest) {
      await prefs.setInt(key, time);
      setState(() {
        if (size == 5) bestTime5x5 = time;
        if (size == 7) bestTime7x7 = time;
        if (size == 9) bestTime9x9 = time;
      });

      // 显示新纪录提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('🎉 新纪录！$size×$size 最好成绩: ${_formatTime(time)}'),
            duration: const Duration(seconds: 4),
            backgroundColor: Colors.purple,
          ),
        );
      }
    }
  }

  void _generateNumbers() {
    int totalNumbers = selectedSize * selectedSize;
    numbers = List.generate(totalNumbers, (index) => index + 1);
    shuffledNumbers = List.from(numbers);
    shuffledNumbers.shuffle(Random());
  }

  void _startGame() {
    setState(() {
      isGameStarted = true;
      isGameCompleted = false;
      currentNumber = 1;
      _seconds = 0;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _seconds++;
      });
    });
  }

  void _stopGame() {
    _timer?.cancel();
    setState(() {
      isGameCompleted = true;
    });
    _saveBestTime(selectedSize, _seconds);

    // 显示完成消息
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('恭喜完成！用时: ${_formatTime(_seconds)}'),
        duration: const Duration(seconds: 3),
        backgroundColor: Colors.green,
      ),
    );
  }

  void _resetGame() {
    _timer?.cancel();
    setState(() {
      isGameStarted = false;
      isGameCompleted = false;
      currentNumber = 1;
      _seconds = 0;
    });
    _generateNumbers();
  }

  void _onNumberPressed(int number) {
    if (!isGameStarted || isGameCompleted) return;

    if (number == currentNumber) {
      setState(() {
        currentNumber++;
      });

      if (currentNumber > selectedSize * selectedSize) {
        _stopGame();
      }
    }
  }

  String _formatTime(int seconds) {
    int minutes = seconds ~/ 60;
    int remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  int? _getBestTime(int size) {
    switch (size) {
      case 5:
        return bestTime5x5;
      case 7:
        return bestTime7x7;
      case 9:
        return bestTime9x9;
      default:
        return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('舒尔特方格训练'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 选择网格大小
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildSizeButton(5),
                _buildSizeButton(7),
                _buildSizeButton(9),
              ],
            ),

            const SizedBox(height: 20),

            // 计时器和状态
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  Text(
                    '时间: ${_formatTime(_seconds)}',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  if (isGameCompleted)
                    const Text(
                      '完成！',
                      style: TextStyle(fontSize: 18, color: Colors.green),
                    ),
                  if (_getBestTime(selectedSize) != null)
                    Text(
                      '最好成绩: ${_formatTime(_getBestTime(selectedSize)!)}',
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.purple,
                      ),
                    ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // 控制按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: isGameStarted ? null : _startGame,
                  child: const Text('开始'),
                ),
                ElevatedButton(
                  onPressed: _resetGame,
                  child: const Text('重新开始'),
                ),
              ],
            ),

            const SizedBox(height: 20),

            // 舒尔特方格
            Expanded(
              child: Center(
                child: AspectRatio(
                  aspectRatio: 1.0,
                  child: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black, width: 2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: GridView.builder(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: selectedSize,
                        crossAxisSpacing: 2,
                        mainAxisSpacing: 2,
                      ),
                      itemCount: selectedSize * selectedSize,
                      itemBuilder: (context, index) {
                        int number = shuffledNumbers[index];
                        bool isVisible = isGameStarted;
                        bool isCompleted = number < currentNumber;

                        return GestureDetector(
                          onTap: () => _onNumberPressed(number),
                          child: Container(
                            decoration: BoxDecoration(
                              color:
                                  isCompleted
                                      ? Colors.green.shade200
                                      : Colors.white,
                              border: Border.all(color: Colors.black),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Center(
                              child: Text(
                                isVisible ? number.toString() : '',
                                style: TextStyle(
                                  fontSize:
                                      selectedSize == 5
                                          ? 24
                                          : selectedSize == 7
                                          ? 20
                                          : 16,
                                  fontWeight: FontWeight.bold,
                                  color:
                                      isCompleted
                                          ? Colors.green.shade800
                                          : Colors.black,
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSizeButton(int size) {
    bool isSelected = selectedSize == size;
    return ElevatedButton(
      onPressed:
          isGameStarted
              ? null
              : () {
                setState(() {
                  selectedSize = size;
                });
                _generateNumbers();
              },
      style: ElevatedButton.styleFrom(
        backgroundColor: isSelected ? Colors.blue : null,
        foregroundColor: isSelected ? Colors.white : null,
      ),
      child: Text('$size×$size'),
    );
  }
}
